<?php
/**
 * Created by PhpStorm.
 * User: 2016-08-23
 * Date: 2017/11/6
 * Time: 10:46
 */
$api_service_path = __DIR__ . "/../../../../api/";
ob_start();
require_once($api_service_path . "public/index.php");
ob_end_clean();
DB::connection()->disableQueryLog(); 
$beijin=1;//北京的城市id
$laiguangying=7;//来广营的门店id
$lgy_mdb=MaintenanceShops::find($laiguangying);
/**
 * 用于金蝶推送账套的保险推送  本脚本 第二个执行
 */

// $mdb=MaintenanceShops::where("status",1)->get();//循环各个门店的入库出库各种记录
// $_date=array(date('Y-m-01', strtotime('-1 month')),date('Y-m-t', strtotime('-1 month')));

// $mdb=MaintenanceShops::where("status",1)->where("id","!=",5)->get();
// $mdb=MaintenanceShops::whereIn("id",array(1))->get();
// $_date=array("2018-07-02","2018-07-31");
// $mdb=MaintenanceShops::whereIn("id",array(1))->get();//循环各个门店的入库出库各种记录
// $_date=array("2018-02-11","2018-02-11");
$mdb=MaintenanceShops::where("status",1)->where("id","!=",5)->get();//循环各个门店的入库出库各种记录
$c_date=date('Y-m-d',time()-86400);//前一天
$_date=array($c_date,$c_date);
// $_date=array("2018-09-01","2018-09-01");
    

Log::useFiles(storage_path().'/logs/kingdee_push.log');

        
$cur_date=floor((strtotime($_date[1])-strtotime($_date[0]))/86400);
for($i=0;$i<=$cur_date;$i++){   
    $date=date('Y-m-d',strtotime($_date[0])+$i*86400);       
    foreach ($mdb as $_mdb) {//
        if(!$_mdb->kingdee_groupid){
            Log::error("门店 ".$_mdb->id."金蝶科目部门异常");
            continue;
        }
        $tkvs=KingdeeVoucherStatus::where("date",$date)->where("type","baoxianchongzhi")->where("shop_id",$_mdb->id)->where("status",1)->first();
        if($tkvs){//如果该门店 该天已经推送过凭证了
            continue;
        }

        $data=array('mainVoucher' =>
            array(
                    
            )
        );
        $entty_array=array();//组织所有的最基层 结构
        $inputjie = array(
            "FAccountID"=>"1243",
            "FExplanation"=>"",
            "FCurrencyID"=>1,
            "FExchangeRate"=>1,
            "FDC"=>1,
            "FAmountFor"=>100,
            "FAmount"=>100,
            "data"=>array(
                "009"=>"114",//商品分类
                "012"=>"001",//直营店
            ),
        );
        $inputdai = array(
            "FAccountID"=>"1243",
            "FExplanation"=>"脚本测试1",
            "FCurrencyID"=>1,
            "FExchangeRate"=>1,
            "FDC"=>0,
            "FAmountFor"=>100,
            "FAmount"=>100,
            "data"=>array(
                "009"=>"114",//商品分类
                "012"=>"001",//直营店
            ),
        );

        $begin_date=date("Y-m-d H:i:s",strtotime($date." 00:00:00")-Config::get("config.report_time_diff"));
        $end_date=date("Y-m-d H:i:s",strtotime($date." 23:59:59")-Config::get("config.report_time_diff"));
        
      
        /**
         * 流水的相关
         */
        $xj_msk=MaintenanceShopKingdee::where("shop_id",$_mdb->id)->where("code","1001")->first();//本门店的现金账套
        if(is_null($xj_msk)){
            Log::error("门店 ".$_mdb->id."现金科目异常");
            continue 1;//有错误数据
        }

        // 保险预存
        $ixj_amount=$iyc_amount=array();     
        $laiguangying_incz=$laiguangying_infx=array();//别的门店记录的来广营的 保险凭证 
        if($_mdb->city_id!=$beijin||$_mdb->id==$laiguangying){//如果是外地 或者来广营
            $iu_array=DB::select("SELECT i.id,i.car_no,i.is_decide,i.cash_amount,i.recharge_amount,i.insurance_type
                FROM insurance i  WHERE i.created_at BETWEEN ?  AND ?
                and website=?
                AND i.`status` = 1", array($begin_date,$end_date,$_mdb->id)); 
            $xj_account=($_mdb->id==$laiguangying?"1001.02":$xj_msk->acount);
            foreach ($iu_array as $_iu) {
                if($_iu->is_decide==1){//说明自定义的 返现
                    assemLiushuiBXFX($ixj_amount,$_iu->cash_amount,$inputjie,$inputdai,$xj_account,$date,$_mdb->kingdee_shopnum,$_mdb->name,$_iu->car_no,'保险优惠自定义');//返现
                    assemLiushuiBXOtYC($iyc_amount,$_iu->recharge_amount,$inputjie,$inputdai,$date,$_mdb->kingdee_shopnum,$_mdb->name,$_iu->car_no,'保险优惠自定义',$_mdb->kingdee_bxcode);//预存
                }else{
                    $pay_array=DB::select("SELECT id.sy_amount,skr.name as sy_name,skr.is_rechange sy_is_rechange,id.jq_amount,jkr.name as jq_name,jkr.is_rechange as jq_is_rechange,cc_amount,ckr.name as cc_name,ckr.is_rechange as ch_is_rechange,id.type from insurance_detail id 
                        LEFT JOIN kickback_rate skr on id.sy_rule=skr.id 
                        LEFT JOIN kickback_rate jkr on id.jq_rule=jkr.id 
                        LEFT JOIN kickback_rate ckr on id.cc_rule=ckr.id  
                        where id.insurance_id=?", array($_iu->id));
                    foreach ($pay_array as $_pr) {
                        if($_pr->type==1){//如果该条是交强险和车船
                            if($_pr->jq_amount>0){
                                if($_pr->jq_is_rechange==1){//说明交强返还预存款
                                    assemLiushuiBXOtYC($iyc_amount,$_pr->jq_amount,$inputjie,$inputdai,$date,$_mdb->kingdee_shopnum,$_mdb->name,$_iu->car_no,'保险优惠'.$_pr->jq_name,$_mdb->kingdee_bxcode);
                                }else{
                                    assemLiushuiBXFX($ixj_amount,$_pr->jq_amount,$inputjie,$inputdai,$xj_account,$date,$_mdb->kingdee_shopnum,$_mdb->name,$_iu->car_no,'保险优惠'.$_pr->jq_name);//返现
                                }
                            }
                            if($_pr->cc_amount>0){
                                if($_pr->ch_is_rechange==1){//说明车船返还预存款
                                    assemLiushuiBXOtYC($iyc_amount,$_pr->cc_amount,$inputjie,$inputdai,$date,$_mdb->kingdee_shopnum,$_mdb->name,$_iu->car_no,'保险优惠'.$_pr->cc_name,$_mdb->kingdee_bxcode);
                                }else{
                                    assemLiushuiBXFX($ixj_amount,$_pr->cc_amount,$inputjie,$inputdai,$xj_account,$date,$_mdb->kingdee_shopnum,$_mdb->name,$_iu->car_no,'保险优惠'.$_pr->cc_name);//返现
                                }
                            }
                        }else{//说明是商业险
                            if($_pr->sy_amount>0){
                                if($_pr->sy_is_rechange==1){//说明商业险返还预存款
                                    assemLiushuiBXOtYC($iyc_amount,$_pr->sy_amount,$inputjie,$inputdai,$date,$_mdb->kingdee_shopnum,$_mdb->name,$_iu->car_no,'保险优惠'.$_pr->sy_name,$_mdb->kingdee_bxcode);
                                }else{
                                    assemLiushuiBXFX($ixj_amount,$_pr->sy_amount,$inputjie,$inputdai,$xj_account,$date,$_mdb->kingdee_shopnum,$_mdb->name,$_iu->car_no,'保险优惠'.$_pr->sy_name);//返现
                                }
                            }
                        }
                    }
                }
            }
            assembleNotsort($data,$ixj_amount,$date,$_mdb);//   
            assembleNotsort($data,$iyc_amount,$date,$_mdb);//        
        }else{//北京的其他门店的 保险凭证
            $iu_array=DB::select("SELECT i.id,i.car_no,i.is_decide,i.cash_amount,i.recharge_amount,i.insurance_type
                FROM insurance i  WHERE i.created_at BETWEEN ?  AND ?
                and website=?
                AND i.`status` = 1", array($begin_date,$end_date,$_mdb->id));                          
            foreach ($iu_array as $_iu) {
                if($_iu->is_decide==1){//说明自定义的
                    assemLiushuiBXFX($laiguangying_infx,$_iu->cash_amount,$inputjie,$inputdai,'1001.02',$date,$lgy_mdb->kingdee_shopnum,$_mdb->name,$_iu->car_no,'保险优惠自定义');//返现  都记到来广营的成本
                    // assemLiushuiBXOtYC($iyc_amount,$_iu->recharge_amount,$inputjie,$inputdai,$date,$_mdb->kingdee_shopnum,$_mdb->name,$_iu->car_no,'保险优惠自定义');//预存
                    assemLiushuiBXBJYC($iyc_amount,$_iu->recharge_amount,$inputjie,$inputdai,$xj_msk->acount,$_mdb->kingdee_shopnum,$_iu->car_no,$_mdb->kingdee_bxcode);//预存
                    assemLiushuiBXFX($laiguangying_incz,$_iu->recharge_amount,$inputjie,$inputdai,'1001.02',$date,$lgy_mdb->kingdee_shopnum,$_mdb->name,$_iu->car_no,'保险优惠'.$_pr->jq_name);
                }else{
                    $pay_array=DB::select("SELECT id.sy_amount,skr.name as sy_name,skr.is_rechange sy_is_rechange,id.jq_amount,jkr.name as jq_name,jkr.is_rechange as jq_is_rechange,cc_amount,ckr.name as cc_name,ckr.is_rechange as ch_is_rechange,id.type from insurance_detail id 
                        LEFT JOIN kickback_rate skr on id.sy_rule=skr.id 
                        LEFT JOIN kickback_rate jkr on id.jq_rule=jkr.id 
                        LEFT JOIN kickback_rate ckr on id.cc_rule=ckr.id  
                        where id.insurance_id=?", array($_iu->id));
                    foreach ($pay_array as $_pr) {
                        if($_pr->type==1){//如果该条是交强险和车船
                            if($_pr->jq_amount>0){
                                if($_pr->jq_is_rechange==1){//说明交强返还预存款
                                    assemLiushuiBXBJYC($iyc_amount,$_pr->jq_amount,$inputjie,$inputdai,$xj_msk->acount,$_mdb->kingdee_shopnum,$_iu->car_no,$_mdb->kingdee_bxcode);//预存
                                    assemLiushuiBXFX($laiguangying_incz,$_pr->jq_amount,$inputjie,$inputdai,'1001.02',$date,$lgy_mdb->kingdee_shopnum,$_mdb->name,$_iu->car_no,'保险优惠'.$_pr->jq_name);
                                }else{
                                    assemLiushuiBXFX($laiguangying_infx,$_iu->jq_amount,$inputjie,$inputdai,'1001.02',$date,$lgy_mdb->kingdee_shopnum,$_mdb->name,$_iu->car_no,'保险优惠'.$_pr->jq_name);//返现  都记到来广营的成本
                                }
                            }
                            if($_pr->cc_amount>0){
                                if($_pr->ch_is_rechange==1){//说明车船返还预存款
                                    assemLiushuiBXBJYC($iyc_amount,$_pr->cc_amount,$inputjie,$inputdai,$xj_msk->acount,$_mdb->kingdee_shopnum,$_iu->car_no,$_mdb->kingdee_bxcode);//预存
                                    assemLiushuiBXFX($laiguangying_incz,$_pr->cc_amount,$inputjie,$inputdai,'1001.02',$date,$lgy_mdb->kingdee_shopnum,$_mdb->name,$_iu->car_no,'保险优惠'.$_pr->cc_name);//返现  都记到来广营的成本
                                }else{
                                    assemLiushuiBXFX($laiguangying_infx,$_pr->cc_amount,$inputjie,$inputdai,'1001.02',$date,$lgy_mdb->kingdee_shopnum,$_mdb->name,$_iu->car_no,'保险优惠'.$_pr->cc_name);//返现  都记到来广营的成本
                                }
                            }
                        }else{//说明是商业险
                            if($_pr->sy_amount>0){
                                if($_pr->sy_is_rechange==1){//说明商业险返还预存款
                                    assemLiushuiBXBJYC($iyc_amount,$_pr->sy_amount,$inputjie,$inputdai,$xj_msk->acount,$_mdb->kingdee_shopnum,$_iu->car_no,$_mdb->kingdee_bxcode);//预存
                                    assemLiushuiBXFX($laiguangying_incz,$_pr->sy_amount,$inputjie,$inputdai,'1001.02',$date,$lgy_mdb->kingdee_shopnum,$_mdb->name,$_iu->car_no,'保险优惠'.$_pr->sy_name);//返现  都记到来广营的成本
                                }else{
                                    assemLiushuiBXFX($laiguangying_infx,$_pr->sy_amount,$inputjie,$inputdai,'1001.02',$date,$lgy_mdb->kingdee_shopnum,$_mdb->name,$_iu->car_no,'保险优惠'.$_pr->sy_name);//返现  都记到来广营的成本
                                }
                            }
                        }
                    }
                }
            }
            //合并 借方
            $depe_temp_dai=null;
            foreach($iyc_amount as $key=>$t){
                if($t['FAccountID']=="1001.01"){
                    if(is_null($depe_temp_dai)){
                        $depe_temp_dai=$t;
                    }else{
                        $depe_temp_dai["FAmountFor"]+=$t['FAmountFor'];
                        $depe_temp_dai["FAmount"]+=$t['FAmount'];
                    }
                    unset($iyc_amount[$key]);
                }
            }
            $temp_iyc_amount=array();
            if(!is_null($depe_temp_dai)){
                $temp_iyc_amount[]=$depe_temp_dai;
            }
            $temp_iyc_amount=array_merge($temp_iyc_amount, $iyc_amount);
            assembleNotsort($data,$temp_iyc_amount,$date,$_mdb);//================================================================================  
            // 
            //合并来广营的贷方
            $depe_temp=null;
            foreach($laiguangying_incz as $key=>$t){
                if($t['FAccountID']=='1001.02'){
                    if(is_null($depe_temp)){
                        $depe_temp=$t;
                    }else{
                        $depe_temp["FAmountFor"]+=$t['FAmountFor'];
                        $depe_temp["FAmount"]+=$t['FAmount'];
                    }
                    unset($laiguangying_incz[$key]);
                }
            }
            if(!is_null($depe_temp)){
                $laiguangying_incz[]=$depe_temp;
            }   
            $depe_temp=null;
            foreach($laiguangying_infx as $key=>$t){
                if($t['FAccountID']=='1001.02'){
                    if(is_null($depe_temp)){
                        $depe_temp=$t;
                    }else{
                        $depe_temp["FAmountFor"]+=$t['FAmountFor'];
                        $depe_temp["FAmount"]+=$t['FAmount'];
                    }
                    unset($laiguangying_infx[$key]);
                }
            }
            if(!is_null($depe_temp)){
                $laiguangying_infx[]=$depe_temp;
            } 
            $laiguangying_in=array_merge($laiguangying_incz, $laiguangying_infx);         
            assembleNotsort($data,$laiguangying_in,$date,$lgy_mdb);//==================================================================         
        }

        
        


        // Log::info($data);
        if(sizeof($data["mainVoucher"])>0){  
            getMaintain($_mdb->id,$data,$date);
            Log::info("门店".$_mdb->id." 日期 ".$date.'完毕');
            echo "门店".$_mdb->id." 日期 ".$date.'完毕';
        }else{
            Log::info("门店".$_mdb->id." 日期 ".$date.'完毕');
            echo "门店".$_mdb->id." 日期 ".$date.'完毕';
        }  
    }
}

/**
 * @Author   lyt                      <ahlyt@anhuibj.com>
 * @DateTime 2018-07-03T15:34:59+0800
 * 用于奖一堆凭证详情拼接成一个凭证 并最终加入 最终的凭证结构体中
 */
function assembleNotsort(&$finally,$value_array,$date,$_mdb){
    if(sizeof($value_array)==0){     
        return $finally;
    }
    $temp =array(
        "FDate"=>$date." 00:00:00",
        "FGroupID"=>$_mdb->kingdee_groupid,//来广营 6
        "FReference"=>null,
        "FAttachments"=>0,
        "FEntryCount"=>4,
        "FDebitTotal"=>0,
        "FCreditTotal"=>0,
        "FPreparerID"=>16428,//写死的制单人
        "FPosterID"=>-1,
        "FTranType"=>0,
        "FTransDate"=>$date." 00:00:00",
        "entryVoucher"=>array(
            
        )           
    );
    $FEntryCount=0;
    $FDebitTotal=0;
    $FCreditTotal=0;
    foreach ($value_array as $value) {  
        $FEntryCount++;
        if($value["FDC"]==1){
            $FDebitTotal+=$value["FAmountFor"];
        }else{
            $FCreditTotal+=$value["FAmountFor"];
        }                           
        $temp["entryVoucher"][]=$value;
    }
    $temp["FEntryCount"]=$FEntryCount;
    $temp["FDebitTotal"]=$FDebitTotal;
    $temp["FCreditTotal"]=$FDebitTotal;
    $finally["mainVoucher"][]=$temp;
    return $finally;
}





//北京所有门店返现 和外地返现
function assemLiushuiBXFX(&$data,$amount,$inputjie,$inputdai,$dai_account,$date,$shop_code,$shop_name,$car_no,$desc){       
    if($amount>0){
        $date=date('m-d',strtotime($date));
        $inputjie["FAccountID"]='5405.01';
        $inputjie["FExplanation"]=$date." ".$shop_name." ".$car_no." ".$desc;
        $inputjie["FAmountFor"]=round($amount/100,2);
        $inputjie["FAmount"]=round($amount/100,2);

        $inputdai["FAccountID"]=$dai_account;
        $inputdai["FExplanation"]="报销 ".$shop_name." 客户保险优惠";  
        $inputdai["FAmountFor"]=round($amount/100,2);
        $inputdai["FAmount"]=round($amount/100,2);

        $datejie=array("012"=>$shop_code);
        $datedai=array();
        
        $inputjie["data"]=$datejie;
        $data[]=$inputjie;      
        $inputdai["data"]=$datedai;
        $data[]=$inputdai;
    }
}
//来广营预存和别的地区的预存
function assemLiushuiBXOtYC(&$data,$amount,$inputjie,$inputdai,$date,$shop_code,$shop_name,$car_no,$desc,$shop_bx_code){       
    if($amount>0){
        $date=date('m-d',strtotime($date));
        $inputjie["FAccountID"]='5405.01';
        $inputjie["FExplanation"]=$date." ".$shop_name." ".$car_no." ".$desc;
        $inputjie["FAmountFor"]=round($amount/100,2);
        $inputjie["FAmount"]=round($amount/100,2);

        $inputdai["FAccountID"]="2181.12";
        $inputdai["FExplanation"]=$car_no." 保险优惠做预收款";  
        $inputdai["FAmountFor"]=round($amount/100,2);
        $inputdai["FAmount"]=round($amount/100,2);

        $datejie=array("012"=>$shop_code);
        $datedai=array("012"=>$shop_code,"017"=>$shop_bx_code);
        
        $inputjie["data"]=$datejie;
        $data[]=$inputjie;      
        $inputdai["data"]=$datedai;
        $data[]=$inputdai;
    }
}
//北京其他门店的预存
function assemLiushuiBXBJYC(&$data,$amount,$inputjie,$inputdai,$jie_account,$shop_code,$car_no,$shop_bx_code){       
    if($amount>0){
        $inputjie["FAccountID"]=$jie_account;
        $inputjie["FExplanation"]=" 保险优惠做预收款";
        $inputjie["FAmountFor"]=round($amount/100,2);
        $inputjie["FAmount"]=round($amount/100,2);

        $inputdai["FAccountID"]="2181.12";
        $inputdai["FExplanation"]=$car_no." 保险优惠做预收款";  
        $inputdai["FAmountFor"]=round($amount/100,2);
        $inputdai["FAmount"]=round($amount/100,2);

        $datejie=array();
        $datedai=array("012"=>$shop_code,"017"=>$shop_bx_code);
        
        $inputjie["data"]=$datejie;
        $data[]=$inputjie;      
        $inputdai["data"]=$datedai;
        $data[]=$inputdai;
    }
}





function getMaintain($shop_id,$data,$date){ 
    $request = array(
        'token' => 1,
        'zhangtao' => "sqlsrv_scs",
        'params' => json_encode($data),
    );

    $response = Httpful::post(Config::get('config.kingdee_local_api')."/kingdeescs/importVoucher")
        ->timeoutIn(15)
        ->body($request)
        ->sendsForm()->send();

    $response = json_decode($response->body);
    Log::info($response->msg);
    $kvs=new KingdeeVoucherStatus();
    $kvs->date=$date;
    $kvs->shop_id=$shop_id;
    $kvs->type="baoxianchongzhi";
    if($response->code==0){//说明成功
        $kvs->status=1;
    }else{
        $kvs->status=0;
    }
    $kvs->save();
}